package cn.yoegg.apps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import cn.yoegg.author.AboutDialog;
import cn.yoegg.login.Login;
import cn.yoegg.utils.HttpUtil;
import cn.yoegg.utils.MyApp;
import cn.yoegg.utils.StringUtil;

import cn.yoegg.mzjw.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author yoegg
 * @time 2014-9-26
 */

public class App_tables extends Activity {

	private TextView userid_show;
	private TextView username_show;
	private Button getKs;
	private Button getCj;
	private Button getKb;
	private Button getTx;

	private String xm = "";
	private String xh = "";
	private String myUrl = "";
	private String[] mTime = null;

	DefaultHttpClient mHttpClient = new DefaultHttpClient();

	private static Boolean isExit = false;
	private static Boolean hasTask = false;
	Timer tExit = new Timer();

	private ProgressDialog m_Dialog = null;
	private Handler handler = new Handler();
	private String[] ss = null;
	private int i = 0;
	private String ksInfo = "";

	private String __VIEWSTATE_xskscx = "";
	private String __VIEWSTATE_xscj_gc = "";

	//Creat apps avtivity
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		//Get layout of application table
		setContentView(R.layout.app_tables);
		Intent get = getIntent();
		xm = get.getBundleExtra("session").getSerializable("xm").toString();
		xh = get.getBundleExtra("session").getSerializable("xh").toString();

		MyApp myApp = (MyApp) getApplication();
		mHttpClient = myApp.getmHttpClient();
		myUrl = myApp.getMyUrl();

		userid_show = (TextView) findViewById(R.id.userid_show);
		userid_show.setText(xh);
		username_show = (TextView) findViewById(R.id.username_show);
		username_show.setText(xm);

		getKs = (Button) findViewById(R.id.getks);
		getCj = (Button) findViewById(R.id.getcj);
		getKb = (Button) findViewById(R.id.getkb);
		getTx = (Button) findViewById(R.id.gettx);

		getKs.setOnClickListener(getKsClick);
		getCj.setOnClickListener(getCjClick);
		getKb.setOnClickListener(getKbClick);
		getTx.setOnClickListener(getTxClick);

	}
	
	//Timing task
	TimerTask task = new TimerTask() {
		public void run() {
			isExit = false;
			hasTask = true;
		}
	};

	//Double click to exit
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if (isExit == false) {
				isExit = true;
				Toast.makeText(getApplicationContext(), R.string.quit_text,
						Toast.LENGTH_SHORT).show();
				if (!hasTask) {
					tExit.schedule(task, 2000);
				}
			} else {
				finish();
				System.exit(0);
			}
			return false;
		}

		return super.onKeyDown(keyCode, event);
	}
	
	//Creat menu
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 2, 2, R.string.about_author).setIcon(
				android.R.drawable.ic_menu_help);
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, R.string.relogin).setIcon(
				android.R.drawable.ic_menu_myplaces);
		return true;
	}
	
	//Add menu item
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case Menu.FIRST + 1:
			Intent intent = new Intent(App_tables.this, Login.class);
			App_tables.this.startActivity(intent);
			App_tables.this.finish();
			break;

		case Menu.FIRST + 2:
			new AboutDialog(this).show();
			break;
		}
		return false;
	}

	//Schedule
	OnClickListener getKbClick = new OnClickListener() {
		String kbInfo = "";

		public void onClick(final View v) {
			m_Dialog = ProgressDialog.show(App_tables.this, "Get data","Wait...", true);
			new Thread(new Runnable() {
				public void run() {
					try {
						kbInfo = HttpUtil.getUrl("http://" + myUrl
								+ "/xskbcx.aspx?xh=" + xh + "&xm=" + xm
								+ "&gnmkdm=N121603", mHttpClient, "http://"
								+ myUrl + "/xs_main.aspx?xh=" + xh);
					} catch (IOException e) {
						e.printStackTrace();
					}
					String temp = kbInfo.replaceAll("</td>", "</td>\n");// 
					Pattern p = Pattern.compile("(?<=>).*(?=</td>)");
					Matcher m = p.matcher(temp);
					ss = null;
					ss = new String[200];
					i = 0;
					while (m.find() && (!m.group().toString().equals("index_number"))) {
						if (!(m.group().toString().equals("&nbsp;"))
								&& !(m.group().toString().equals(""))
								&& !(m.group().toString().equals("morning"))
								&& !(m.group().toString().equals("am"))
								&& !(m.group().toString().equals("pm"))
								&& !(m.group().toString().equals("night"))
								&& !(m.group().toString().substring(0, 1).equals("star"))
								&& !(m.group().toString().equals("time"))
								&& !(m.group().toString().substring(0, 1).equals("no."))) {
							ss[i] = m.group().toString();
							i++;
						}
					}

					// 
					handler.post(new Runnable() {
						public void run() {
							Context context = v.getContext();
							Intent intent = new Intent(context, List_kb.class);
							Bundle b = new Bundle();
							b.putStringArray("ss", ss);
							b.putInt("i", i);
							intent.putExtras(b);
							context.startActivity(intent);
						}
					});

					m_Dialog.dismiss();
				}
			}).start();
		}

	};
	
	//Exam
	OnClickListener getKsClick = new OnClickListener() {
		String __VIEWSTATE = "";
		StringTokenizer tokenizer = null;
		String xqd = "";
		String xnd = "";
		String[] ss = null;
		int i = 0;

		public void onClick(final View v) {

			ss = new String[100];					
			mTime = new String[] { "2011-2012 First Semester", "2011-2012 Second Semester", 
								   "2012-2013 First Semester","2012-2013 Second Semester", 
								   "2013-2014 First Semester","2013-2014 Second Semester" };
			
			new AlertDialog.Builder(App_tables.this)
					.setTitle("Choices")
					.setItems(mTime, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,final int whichTime) {
							m_Dialog = ProgressDialog.show(App_tables.this,"Get data", "waitting...", true);
							new Thread(new Runnable() {
								public void run() {
									if (__VIEWSTATE_xskscx == "") {
										try {
											ksInfo = HttpUtil.getUrl(
													"http://"
															+ myUrl
															+ "/xskscx.aspx?xh="
															+ xh + "&xm=" + xm
															+ "&gnmkdm=N121604",mHttpClient,
															"http://"
																	+ myUrl
																	+ "/xs_main.aspx?xh="
																	+ xh);
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}

										if (ksInfo != "") {
											tokenizer = new StringTokenizer(
													ksInfo);
											while (tokenizer.hasMoreTokens()) {
												String valueToken = tokenizer
														.nextToken();
												// System.out.println(valueToken);
												if (StringUtil.isValue(
														valueToken, "value")
														&& valueToken.length() > 100) {
													if (StringUtil.getValue(
															valueToken,
															"value", "\"", 7)
															.length() > 100) {
														__VIEWSTATE = StringUtil
																.getValue(
																		valueToken,
																		"value",
																		"\"", 7);// value
														__VIEWSTATE_xskscx = __VIEWSTATE;

													}
												}
											}
										}

									}
									if (__VIEWSTATE_xskscx != "") {
										__VIEWSTATE = __VIEWSTATE_xskscx;

									}
									ss = new String[100];
									i = 0;
									List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
									if (whichTime == 0) {
										xnd = "2011-2012";
										xqd = "1";
									}
									if (whichTime == 1) {
										xnd = "2011-2012";
										xqd = "2";
									}
									if (whichTime == 2) {
										xnd = "2012-2013";
										xqd = "1";
									}
									if (whichTime == 3) {
										xnd = "2012-2013";
										xqd = "2";
									}
									if (whichTime == 4) {
										xnd = "2013-2014";
										xqd = "1";
									}
									if (whichTime == 5) {
										xnd = "2013-2014";
										xqd = "2";
									}
									pairs.add(new BasicNameValuePair(
											"__EVENTTARGET", "xqd"));
									pairs.add(new BasicNameValuePair(
											"__EVENTARGUMENT", null));
									pairs.add(new BasicNameValuePair(
											"__VIEWSTATE", __VIEWSTATE));
									pairs.add(new BasicNameValuePair("xnd", xnd));
									pairs.add(new BasicNameValuePair("xqd", xqd));

									String info = "";
									try {
										info = HttpUtil.postUrl("http://"
												+ myUrl + "/xskscx.aspx?xh="
												+ xh + "&xm=" + xm
												+ "&gnmkdm=N121604", pairs,
												mHttpClient, "http://" + myUrl
														+ "/xskscx.aspx?xh="
														+ xh + "&xm=" + xm
														+ "&gnmkdm=N121604");
									} catch (ClientProtocolException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

									if (info != null) {

										String temp = info.replaceAll("</td>","</td>\n");
										Pattern p = Pattern.compile("(?<=<td>).*(?=</td>)");
										Matcher m = p.matcher(temp);
										while (m.find()) {
											ss[i] = m.group().toString();
											i++;
										}

									}

									// 
									handler.post(new Runnable() {
										public void run() {
											Context context = v.getContext();
											Intent intent = new Intent(context,
													List_ks.class);
											Bundle b = new Bundle();
											b.putStringArray("ss", ss);
											b.putInt("i", i);
											intent.putExtras(b);
											context.startActivity(intent);
											Toast.makeText(
													getApplicationContext(),
													"Choose item to preview",
													Toast.LENGTH_SHORT).show();
										}
									});
									m_Dialog.dismiss();
								}
							}).start();

						}
					})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface d, int which) {
									d.dismiss();
								}
							}).show();
		}
	};

	//Score
	OnClickListener getCjClick = new OnClickListener() {
		String __VIEWSTATE = "";
		StringTokenizer tokenizer = null;
		String ddlXN = "";
		String ddlXQ = "";
		String[] ss = null;
		int i = 0;

		public void onClick(final View v) {

			mTime = new String[] { "2011-2012 term1", "2011-2012 term2", 
					"2012-2013 term1","2012-2013 term2", 
					"2013-2014 term1","2013-2014 term2" };
			new AlertDialog.Builder(App_tables.this)
					.setTitle("choose trem")
					.setItems(mTime, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								final int whichTime) {

							m_Dialog = ProgressDialog.show(App_tables.this,
									"wait", "get data...", true);

							new Thread(new Runnable() {

								public void run() {
									if (__VIEWSTATE_xscj_gc == "") {

										try {
											ksInfo = HttpUtil.getUrl(
														"http://"
															+ myUrl
															+ "/xscj_gc.aspx?xh="
															+ xh + "&xm=" + xm
															+ "&gnmkdm=N121605",
															mHttpClient,
															"http://"
																	+ myUrl
																	+ "/xs_main.aspx?xh="
																	+ xh);
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}

										if (ksInfo != "") {
											tokenizer = new StringTokenizer(
													ksInfo);
											while (tokenizer.hasMoreTokens()) {
												String valueToken = tokenizer
														.nextToken();
												// System.out.println(valueToken);
												if (StringUtil.isValue(
														valueToken, "value")
														&& valueToken.length() > 100) {
													if (StringUtil.getValue(valueToken,"value", "\"", 7).length() > 100) {
														__VIEWSTATE = StringUtil.getValue(valueToken,"value","\"", 7);// value
														__VIEWSTATE_xscj_gc = __VIEWSTATE;
													}
												}
											}
										}

									}
									if (__VIEWSTATE_xscj_gc != "") {
										__VIEWSTATE = __VIEWSTATE_xscj_gc;

									}

									ss = new String[500];
									i = 0;
									List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
									// System.out.println(__VIEWSTATE);
									if (whichTime == 0) {
										ddlXN = "2011-2012";
										ddlXQ = "1";
									}
									if (whichTime == 1) {
										ddlXN = "2011-2012";
										ddlXQ = "2";
									}
									if (whichTime == 2) {
										ddlXN = "2012-2013";
										ddlXQ = "1";
									}
									if (whichTime == 3) {
										ddlXN = "2012-2013";
										ddlXQ = "2";
									}
									if (whichTime == 4) {
										ddlXN = "2013-2014";
										ddlXQ = "1";
									}
									if (whichTime == 5) 
									{
										ddlXN = "2013-2014";
										ddlXQ = "2";
									}
									pairs.add(new BasicNameValuePair(
											"__VIEWSTATE", __VIEWSTATE));
									pairs.add(new BasicNameValuePair("ddlXN",
											ddlXN));
									pairs.add(new BasicNameValuePair("ddlXQ",
											ddlXQ));
									pairs.add(new BasicNameValuePair("Button1",
											"%B0%B4%D1%A7%C6%DA%B2%E9%D1%AF"));
									
									String info = "";
									try 
									{
										info = HttpUtil.postUrl("http://"
												+ myUrl + "/xscj_gc.aspx?xh="
												+ xh + "&xm=" + xm
												+ "&gnmkdm=N121605", pairs,
												mHttpClient, "http://" + myUrl
														+ "/xscj_gc.aspx?xh="
														+ xh + "&xm=" + xm
														+ "&gnmkdm=N121605");
									} 
									catch (ClientProtocolException e) 
									{
										e.printStackTrace();
									} 
									catch (IOException e) 
									{
										e.printStackTrace();
									}

									if (info != "") {

										String temp = info.replaceAll("</td>",
												"</td>\n");// 
										Pattern p = Pattern
												.compile("(?<=<td>).*(?=</td>)");
										Matcher m = p.matcher(temp);

										while (m.find()
												&& (!m.group().toString()
														.equals("aa"))) {

											ss[i] = m.group().toString();
											i++;
										}

									}

									// 
									handler.post(new Runnable() {
										public void run() {
											Context context = v.getContext();
											Intent intent = new Intent(context,
													List_cj.class);
											Bundle b = new Bundle();
											b.putStringArray("ss", ss);
											b.putInt("i", i);
											intent.putExtras(b);
											context.startActivity(intent);
											Toast.makeText(
													getApplicationContext(),
													"Choose item to preview",
													Toast.LENGTH_SHORT).show();
										}
									});

									m_Dialog.dismiss();
								}
							}).start();

						}
					})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface d, int which) {
									d.dismiss();
								}
							}).show();
		}
	};
	
	//Avatar 
	OnClickListener getTxClick = new OnClickListener() {
		byte[] txInfo;

		public void onClick(final View v) {
			m_Dialog = ProgressDialog.show(App_tables.this, "wait",
					"get data...", true);

			new Thread(new Runnable() {

				public void run() {
					try {
						txInfo = HttpUtil.getUrl_byte("http://" + myUrl
								+ "/readimagexs.aspx?xh=" + xh, mHttpClient,
								"http://" + myUrl + "/xs_main.aspx?xh=" + xh);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//
					handler.post(new Runnable() {
						public void run() {
							Context context = v.getContext();
							Intent intent = new Intent(context, List_tx.class);
							Bundle b = new Bundle();
							b.putByteArray("txInfo", txInfo);
							b.putString("xh", xh);
							intent.putExtras(b);
							context.startActivity(intent);
						}
					});

					m_Dialog.dismiss();
				}
			}).start();
		}

	};
}
